package com.mano.demo;


import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.*;

/**
 * @Author: zj
 * @Description:
 * @Date: Created in 15:54 2020/9/4
 * @Modified By:
 */
public class DownLoadFile {

    /**
     *
     * @param url
     * @param contentType
     * @return
     */
    public String getFileNameByUrl(String url,String contentType){
        // 移除 http:
        url = url.substring(7);
        if(contentType.indexOf("html")!=-1){
            url = url.replaceAll("[\\?/:*|<>\"]","_")+".html";
            return url;
        }else{
            // 比如 application/pdf类型
            return url.replaceAll("[\\?/:*|<>\"]","_")+"."+contentType.substring(contentType.lastIndexOf("/")+1);
        }
    }

    /**
     * 保存网页字节数到本地文件
     * @param data
     * @param filePath 是要保存的文件的相对地址
     */
    private void saveToLocal(byte[] data,String filePath){
        try {
            File file = new File(filePath);
            if(!file.exists()){
                file.getParentFile().mkdirs();
            }
            DataOutputStream outputStream = new DataOutputStream(new FileOutputStream(file));
            for (int i = 0; i < data.length ; i++) {
                outputStream.write(data[i]);
            }
            //flush()这个方法是清空的意思，用来清空缓冲区中的数据流
            outputStream.flush();
            outputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载网页指向的url
     * @param url
     * @return
     */
    public String downLoadFile(String url){

        String filePath=null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).build();

        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(requestConfig);


        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);

            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode != HttpStatus.SC_OK){
                System.err.println("Method failed"+ statusCode);
                filePath = null;
            }



            byte[] bytes = EntityUtils.toByteArray(response.getEntity());
            filePath= "temp\\"+getFileNameByUrl(url,response.getEntity().getContentType().getValue());
//            filePath= System.getProperty("user.dir")+"\\temp\\"+getFileNameByUrl(url,response.getEntity().getContentType().getValue());
            saveToLocal(bytes,filePath);


        } catch (IOException e) {
            e.printStackTrace();
        }
        return filePath;
    }
}
